package com.lhdx.practical.controllers;

import com.alibaba.fastjson.JSONObject;
import com.lhdx.practical.bean.Content;
import com.lhdx.practical.bean.Menu;
import com.lhdx.practical.bean.MenuConfig;
import com.lhdx.practical.bean.Person;
import com.lhdx.practical.config.UploadConfig;
import com.lhdx.practical.dao.MenuDao;
import com.lhdx.practical.service.ContentService;
import com.lhdx.practical.service.MenuConfigService;
import com.lhdx.practical.service.PersonService;
import com.lhdx.practical.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/function/content")
public class ContentController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private PersonService personService;
    @Autowired
    private ContentService contentService;
    @Autowired
    private UploadConfig uploadConfig;
    /**
     * 基础列表
     * @return
     */
    @GetMapping("/basicslist")
    public ModelAndView basicslist(long mid, long sid,long gradeid, HttpServletResponse response) {
        long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
        Person person = personService.findById(userid);
        try {
            //跳转任务清单
            if(sid == 201911151263870009L){
                List<Content> contentList = contentService.findAllBySidAndMidAndGradeid(sid,mid,gradeid);
                if(contentList.size() == 0){
                    //暂无任务清单 添加
                    Content content = new Content(0,mid,sid,gradeid,0,"","","",person);
                    contentService.save(content);
                    contentList.add(content);
                }
                //老师去往编辑页面
                if(person.getType() == 1){
                    response.sendRedirect("update?id="+contentList.get(0).getId());
                }else if(person.getType() == 2){
                    //学生去往展示页面
                    response.sendRedirect("detail?id=" + contentList.get(0).getId());
                }
            }else if(sid == 201911151263870013L){
                //跳转团队贡献评价
                List<Content> contentList = contentService.findAllBySid(sid);
                //老师去往编辑页面
                if(person.getType() == 1){
                    response.sendRedirect("../fraction/evaluate?mid="+mid+"&sid="+sid+"&gradeid="+gradeid);
                }else if(person.getType() == 2){
                    //学生去往互评页面
                    response.sendRedirect("../fraction/evaluation?mid="+mid+"&sid="+sid+"&gradeid="+gradeid);
                }
            }else if(sid == 201911151263870012L){
                if(person.getType() == 1){
                    response.sendRedirect("../task/teacherList?mid="+mid+"&sid="+sid+"&gradeid="+gradeid);
                }else if(person.getType() == 2){
                    //学生去往上传作业
                    response.sendRedirect("../task/list?mid="+mid+"&sid="+sid+"&gradeid="+gradeid);
                }
            }else if(sid == 201911151263870014L && person.getType() == 1){
                response.sendRedirect("../fraction/performance?mid="+mid+"&sid="+sid+"&gradeid="+gradeid);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Menu menu = menuDao.findById(mid);
        Menu smenu = menuDao.findById(sid);
        int page = StrUtils.getInt(request,"p",1);

        String url = "content/basicslist";
        int orderby = 0;
        //学生跳转流程模拟图
        int gotype = StrUtils.getInt(request,"gotype",0);
        if((person.getType() == 2 && sid == 201911151263870008L) || gotype == 1){
            url = "content/flowchart";
        }
        //流程模拟图排序
        if(sid == 201911151263870008L){
            orderby = 1;
        }
        Map<String,String> searchmap = new HashMap<>();
        searchmap.put("mid",mid+"");
        searchmap.put("sid",sid+"");
        searchmap.put("gradeid",gradeid+"");
        PageVo<Content> pageResult = new PageVo<Content>(page,searchmap,contentService.getResultList(mid,sid,gradeid,orderby,page,Constants.pagesize));
        return new ModelAndView(url)
                .addObject("menu",menu)
                .addObject("smenu",smenu)
                .addObject("personType",person.getType())
                .addObject("pageResult",pageResult)
                .addObject("gradeid",gradeid)
                .addObject("gotype",gotype);
    }

    @GetMapping("/addContent")
    public ModelAndView addContent(long mid,long sid,long gradeid) {
        long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
        Person person = personService.findById(userid);
        Menu menu = menuDao.findById(mid);
        Menu smenu = menuDao.findById(sid);
        return new ModelAndView("content/addContent")
                .addObject("menu",menu)
                .addObject("smenu",smenu)
                .addObject("gradeid",gradeid)
                .addObject("personType",person.getType())
                .addObject("sortid",201911151263870008L);
    }

    @GetMapping("/update")
    public ModelAndView update(long id) {
        Content content = contentService.findOne(id);
        Menu menu = menuDao.findById(content.getMid());
        Menu smenu = menuDao.findById(content.getSid());
        return new ModelAndView("content/updateContent")
                .addObject("content",content)
                .addObject("menu",menu)
                .addObject("smenu",smenu)
                .addObject("sortid",201911151263870008L);
    }

    @GetMapping("/evaluate")
    public ModelAndView evaluate(long mid,long sid,long gradeid) {
        Menu menu = menuDao.findById(mid);
        Menu smenu = menuDao.findById(sid);
        Content content = contentService.findByGradeidAndSid(gradeid,sid);
        if(content == null){
            long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            Person person = personService.findById(userid);
            content = new Content(0,mid,sid,gradeid,0,"","","",person);
            contentService.save(content);
        }
        return new ModelAndView("content/evaluate")
                .addObject("content",content)
                .addObject("menu",menu)
                .addObject("smenu",smenu);
    }


    /**
     * 内容详情
     * @param id
     * @return
     */
    @GetMapping("/detail")
    public ModelAndView detail(long id) {
        Content content = contentService.findOne(id);
        Menu menu = menuDao.findById(content.getMid());
        Menu smenu = menuDao.findById(content.getSid());
        contentService.updateClicks(content.getId(),content.getClicks()+1);
        content.setClicks(content.getClicks()+1);
        return new ModelAndView("content/detail")
                .addObject("content",content)
                .addObject("menu",menu)
                .addObject("smenu",smenu);
    }

    /**
     * 删除内容
     * @return
     */
    @CrossOrigin
    @PostMapping("delete")
    @ResponseBody
    public String delete(long id) {
        JSONObject jsonObject = new JSONObject();
        try {
            long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            Person person = personService.findById(userid);
            if(person.getType() == 1){
                contentService.deleteById(id);
                jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"删除成功","");
            }else{
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"验证失败","");
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"删除失败","");
        }
        return jsonObject.toString();
    }

    /**
     * 添加/修改内容
     * @return
     */
    @CrossOrigin
    @PostMapping("toadd")
    @ResponseBody
    public String toadd(long id,long mid,long sid,long gradeid,int sort,String title,String detail,String attachments) {
        JSONObject jsonObject = new JSONObject();
        try {
            long userid = Long.parseLong(CookieUtils.getCookieByNameValue(request, Constants.LOGINED));
            Person person = personService.findById(userid);
            if(person.getType() == 1){
                if(id == 0){
                    Content content = new Content(0,mid,sid,gradeid,sort,title,detail,attachments,person);
                    contentService.save(content);
                }else{
                    Content content = contentService.findOne(id);
                    content.setTitle(title);
                    content.setSort(sort);
                    content.setAttachments(attachments);
                    content.setDetail(detail);
                    contentService.save(content);
                }
                jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"添加成功","");
            }else{
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"验证失败","");
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"添加失败","");
        }
        return jsonObject.toString();
    }


    /**
     * 下载附件
     * @return
     */
    @CrossOrigin
    @GetMapping(value="/downloadContent",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String downloadContent(long id,HttpServletResponse response) throws Exception{
        JSONObject jsonObject = new JSONObject();
        try {
            Content content = contentService.findOne(id);
            if(content.getAttachments() != null && content.getAttachments().length() > 1){
                contentService.updateDownloads(content.getId(),content.getDownloadcount()+1);
                String[] filename = content.getAttachments().split("/");
                FileUtil.downloadFile(request,response,filename[filename.length-1],uploadConfig.getUploadPath()+content.getAttachments());

            }
            System.out.println(content.getAttachments());

            //response.sendRedirect(URLEncoder.encode(content.getAttachments(),"UTF-8"));
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"添加失败","");
        }
        return jsonObject.toString();
    }

    //上传附件
    @CrossOrigin
    @PostMapping("uploadContent")
    @ResponseBody
    public String uploadTask(@RequestParam("file") MultipartFile file, String mname, String sname,long sid) {
        JSONObject jsonObject = new JSONObject();
        if (!file.isEmpty()) {
            String url = "";
            try {
                String fileName = file.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                fileName = mname + "-" + sname + "-"+(contentService.findAllBySid(sid).size()+1);
                url = "/files/"+fileName + "."+ suffix;
                FileUtil.uploadFile(file.getBytes() , uploadConfig.getUploadPath()+"/files/", fileName + "."+ suffix);
            } catch (Exception e) {
                e.printStackTrace();
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"文件上传失败","");
            }
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"上传成功",url);
        } else {
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"文件不存在","");
        }
        return jsonObject.toJSONString();
    }
}
